package com.wzy.alllearning.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.google.common.util.concurrent.RateLimiter;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class RateLimitInterceptor implements HandlerInterceptor
{
	// 设定qps为100 （每秒查询率）
	private static final RateLimiter RATE_LIMITER = RateLimiter.create(100);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
	{
		// return HandlerInterceptor.super.preHandle(request, response, handler);
		if (!RATE_LIMITER.tryAcquire())
		{
			log.error("系统已被限流");
			// 抛出异常返回
			return false;
		}
		return true;
	}
}
